<template>
  <div class="fullMain" style="max-height: calc(100% - 50px);overflow: scroll;">
    <div style="position:fixed; width:100%; z-index:999">
      <x-header :left-options="{backText: '',showBack: false}">
        <span style="color: #D9D9D9;font-size: 17px">设备资产</span>
      </x-header>
    </div>
    <div style="height:46px" />
    <!--插入验证提示框-->
    <div v-transfer-dom>
      <alert v-model="isShowAlert">{{alertText}}</alert>
    </div>
    <div v-transfer-dom>
      <confirm
        v-model="isShowConfirm"
        title="确定报废此设备吗？"
        @on-cancel="isShowConfirm=false"
        @on-confirm="invalidAsset()"
      ></confirm>
    </div>
    <group>
      <search
        @on-change="getResult"
        v-model="searchKey"
        position="absolute"
        top="0px"
        auto-scroll-to-top
        ref="search"
      ></search>
      <cell
        title="申请设备"
        is-link
        :arrow-direction="showApplyForDevice ? 'up' : 'down'"
        @click.native="showApplyForDevice = !showApplyForDevice"
      ></cell>
      <template v-if="showApplyForDevice">
        <div class="applyForDevice">
          <x-input title="资产名：" :show-clear="false" v-model="assetName" text-align="right"></x-input>
          <div class="assetType">
            <x-input title="资产类型：" disabled></x-input>
            <span :class="assetType === '电子设备'?'selected':''" @click="assetType = '电子设备'">电子设备</span>
            <span :class="assetType === '服务器'?'selected':''" @click="assetType = '服务器'">服务器</span>
            <span :class="assetType === '办公设施'?'selected':''" @click="assetType = '办公设施'">办公设施</span>
            <span :class="assetType === '书籍'?'selected':''" @click="assetType = '书籍'">书籍</span>
            <span :class="assetType === '其他'?'selected':''" @click="assetType = '其他'">其他</span>
          </div>
          <x-input title="资产型号：" :show-clear="false" v-model="assetNo" text-align="right"></x-input>
          <x-input title="资产数量：" :show-clear="false" v-model="assetNumber" text-align="right"></x-input>
          <datetime v-model="applyDate" title="申请时间："></datetime>
          <x-textarea title="用途：" :show-clear="false" v-model="useFor" text-align="right"></x-textarea>
          <div style="text-align:center;">
            <x-button mini style="margin-right:10px" @click.native="cancle()">取消</x-button>
            <x-button mini @click.native="submit()">提交</x-button>
          </div>
        </div>
      </template>

      <cell
        title="设备使用情况"
        is-link
        :border-intent="false"
        :arrow-direction="showDeviceContent ? 'up' : 'down'"
        @click.native="showDeviceContent = !showDeviceContent"
      ></cell>
      <template v-if="showDeviceContent && devicesContent.length !== 0 && searchKey===''">
        <div class="deviceContent">
          <div v-for="(item,index) in devicesContent" :key="index">
            <cell
              :title="item[0].assetName"
              :border-intent="false"
              is-link
              :arrow-direction="showDeviceContentDetail&& choosedIndex===index ? 'up' : 'down'"
              @click.native="getDetail(item[0],index)"
            >
              <span>{{item[0].userName}}</span>&nbsp;
              <span>{{getReturnInfo(item[0].returnDate,item[0].receiverId)}}</span>
              <x-button
                v-if="item[0].userId == userInfo.userId && item[0].returnDate=='未归还'"
                mini
                @click.native="isShowReturn = !isShowReturn"
              >转让/报废</x-button>
            </cell>
            <div v-if="showDeviceContentDetail && choosedIndex===index" class="deviceContentDetail">
              <div>
                <span>资产名：</span>
                <span>{{item[0].assetName}}</span>
              </div>
              <div>
                <span>资产类型：</span>
                <span>{{item[0].assetType}}</span>
              </div>
              <div>
                <span>资产型号：</span>
                <span>{{item[0].assetNo}}</span>
              </div>
              <div>
                <span>资产数量：</span>
                <span>{{item[0].assetNumber}}</span>
              </div>
              <div>
                <span>用途：</span>
                <span>{{item[0].purpose}}</span>
              </div>
              <ul class="applyUserInfoList">
                <li class="applyUserInfoListLi" v-for="(item_in,index_in) in item" :key="index_in">
                  <div class="applyUserInfo">
                    <span>{{item_in.userName}}</span>
                    <span>{{item_in.applyDate}}</span>
                    <span>{{item_in.returnDate}}</span>
                  </div>
                  <i class="fa fa-arrow-right" v-if="index_in !== 0"></i>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </template>
      <!-- 搜索的结果 -->
      <template v-if="showDeviceContent && searchKey !==''">
        <div class="deviceContent">
          <div v-for="(item,index) in searchResults" :key="index">
            <cell
              :title="item.assetName"
              :border-intent="false"
              is-link
              :arrow-direction="showSearchDetail && choosedIndex===index ? 'up' : 'down'"
              @click.native="getDetail(item,index)"
            >
              <span>{{item.userName}}</span>&nbsp;
              <span>{{getReturnInfo(item.returnDate,item.receiverId)}}</span>
              <x-button
                v-if="item.userId == userInfo.userId && item.returnDate=='未归还'"
                mini
                @click.native="isShowReturn = !isShowReturn"
              >转让/报废</x-button>
            </cell>
            <div v-if="showSearchDetail && choosedIndex===index" class="deviceContentDetail">
              <div>
                <span>资产名：</span>
                <span>{{item.assetName}}</span>
              </div>
              <div>
                <span>资产类型：</span>
                <span>{{item.assetType}}</span>
              </div>
              <div>
                <span>资产型号：</span>
                <span>{{item.assetNo}}</span>
              </div>
              <div>
                <span>资产数量：</span>
                <span>{{item.assetNumber}}</span>
              </div>
              <div>
                <span>申领人：</span>
                <span>{{item.userName}}</span>
              </div>
              <div>
                <span>申领日期：</span>
                <span>{{item.applyDate}}</span>
              </div>
              <div>
                <span>归还日期：</span>
                <span>{{item.returnDate}}</span>
              </div>
              <div v-if="item.receiverName !== '无'">
                <span>接手人：</span>
                <span>{{item.receiverName}}</span>
              </div>
              <div>
                <span>用途：</span>
                <span>{{item.purpose}}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
      <div v-if="assetsListUser.length == 0 && devicesContent.length == 0" class="deviceContent">
        <cell title="暂无申领设备" :border-intent="false"></cell>
      </div>
    </group>
    <div class="transferAsset" v-if="isShowReturn">
      <x-input
        title="转交给："
        placeholder="此处必填"
        :show-clear="false"
        v-model="searchUser"
        text-align="right"
      ></x-input>
      <radio v-if="isShowChooseList" class="chooseList" :options="chooseList" v-model="choosedUser"></radio>
      <x-input disabled placeholder="请慎重选择，无法更改！" text-align="left"></x-input>
      <div style="text-align:center;">
        <x-button mini style="margin-right:10px" @click.native="isShowReturn = false">取消</x-button>
        <x-button mini @click.native="returnAsset()">转交</x-button>
        <x-button mini @click.native="isShowConfirm = !isShowConfirm">报废</x-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  XHeader,
  Cell,
  Group,
  CellBox,
  XInput,
  XTextarea,
  XButton,
  Radio,
  Checker,
  CheckerItem,
  Datetime,
  Search,
  Confirm
} from "vux";
import { mapState } from "Vuex";
import group_asset from "api/group_asset";

export default {
  name: "ReportAssets",
  data() {
    return {
      alertText: "", // 验证提示框的文本
      isShowAlert: false, // 是否显示验证提示框
      isShowConfirm: false,
      showDeviceContent: true,
      showDeviceContentDetail: false,
      showSearchDetail:false,
      showApplyForDevice: false,
      groupId: this.$route.params.groupId,
      groupMembers: this.$route.params.groupMembers,
      choosedIndex: 0,
      choosedItem: {},
      assetName: "",
      assetType: "电子设备",
      assetNo: "",
      assetNumber: 1,
      useFor: "",
      devicesContent: [],
      searchUser: "",
      choosedUser: "",
      chooseList: [],
      isShowChooseList: false,
      isShowReturn: false,
      assetsListUser: [],
      applyDate: "",
      applyList: [],
      searchResults: [],
      searchKey: ""
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    ...mapState(["isGroupOwner", "isGroupAdmin"]),
    groupUsers() {
      let arr = [];
      for (let i in this.groupMembers) {
        let userName = this.groupMembers[i].detail.name;
        let userId = this.groupMembers[i].userId;
        arr.push({ key: userId, value: userName });
      }
      return arr;
    }
  },
  mounted() {
    this.applyDate = this.getToday();
    this.getAssets();
    this.getApplyList();
  },
  watch: {
    searchUser(val) {
      if (val !== "") {
        this.isShowChooseList = true;
        this.getChooseList();
      } else {
        this.isShowChooseList = false;
        this.choosedUser = "";
      }
    },
    choosedUser(val) {
      console.log("choosedUser变了：" + val);
      if (val !== "") {
        this.isShowChooseList = false;
        for (let i in this.groupUsers) {
          if (this.groupUsers[i].key === val) {
            this.searchUser = this.groupUsers[i].value;
          }
        }
      }
    }
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    showAlert(alertText) {
      this.isShowAlert = true;
      this.alertText = alertText;
    },
    closeTip() {
      this.isShowAlert = false;
      this.alertText = "";
    },
    getToday() {
      let now = new Date();
      let cmonth = now.getMonth() + 1;
      let day = now.getDate();
      let hour = now.getHours();
      if (cmonth < 10) cmonth = "0" + cmonth;
      if (day < 10) day = "0" + day;
      return now.getFullYear() + "-" + cmonth + "-" + day;
    },
    getChooseList() {
      this.chooseList = [];
      for (let i in this.groupUsers) {
        if (this.groupUsers[i].value.indexOf(this.searchUser) !== -1) {
          this.chooseList.push(this.groupUsers[i]);
        }
      }
      console.log(this.chooseList);
    },
    async getAssets() {
      const result = await group_asset.getAssetsByGroupId(this.groupId);
      if (result.code === 0) {
      } else {
        this.devicesContent = result.data;
      }
    },
    async getApplyList() {
      const result = await group_asset.getApplyListByGroupId(this.groupId);
      if (result.code === 0) {
      } else {
        this.applyList = result.data;
      }
    },
    async submit() {
      if (this.assetName == "") {
        this.showAlert("请填写【资产名】");
        setTimeout(this.closeTip, 1000);
        return;
      } else if (this.assetType == "") {
        this.showAlert("请填写【资产类型】");
        setTimeout(this.closeTip, 1000);
        return;
      } else if (this.assetNo == "") {
        this.showAlert("请填写【资产型号】");
        setTimeout(this.closeTip, 1000);
        return;
      } else if (this.assetNumber == "") {
        this.showAlert("请填写【资产数量】");
        setTimeout(this.closeTip, 1000);
        return;
      } else {
        const result = await group_asset.postApplyForAsset({
          applyDate: this.applyDate,
          assetName: this.assetName,
          assetNo: this.assetNo,
          assetNumber: this.assetNumber,
          assetType: this.assetType,
          groupId: this.groupId,
          groupName: "",
          returnDate: "",
          userId: this.userInfo.userId,
          userName: this.userInfo.userName,
          purpose: this.useFor
        });
        if (result.code === 0) {
        } else {
          this.showAlert("申领成功!");
          setTimeout(this.closeTip, 1000);
          this.getAssets();
          this.showApplyForDevice = false;
          this.assetName = "";
          this.assetNo = "";
          this.assetType = "";
          this.useFor = "";
        }
      }
    },
    cancle() {
      this.showApplyForDevice = false;
      this.assetName = "";
      this.assetNo = "";
      this.assetType = "";
      this.useFor = "";
    },
    getReturnInfo(returnDate, receiverId) {
      let result;
      if (returnDate == "未归还") {
        result = "正在使用";
      } else if (receiverId == null) {
        result = "已报废";
      } else {
        result = "已转让";
      }
      return result;
    },
    async returnAsset() {
      if (this.choosedUser == "") {
        this.showAlert("请选择【接手人】");
      } else {
        const result = await group_asset.getTransferAssets(
          this.choosedItem.assetId,
          this.choosedUser
        );
        if (result.code === 0) {
          this.showAlert(result.message);
          setTimeout(this.closeTip, 1000);
        } else {
          this.showAlert("转交成功");
          setTimeout(this.closeTip, 1000);
          this.isShowReturn = false;
          this.getAssets();
        }
      }
    },
    async invalidAsset() {
      const result = await group_asset.getReturnAssets({
        assetId: this.choosedItem.assetId
      });
      if (result.code === 0) {
        this.showAlert("报废失败，请稍后再试！");
        setTimeout(this.closeTip, 1000);
      } else {
        this.showAlert("报废成功");
        setTimeout(this.closeTip, 1000);
        this.isShowReturn = false;
        this.getAssets();
      }
    },
    getDetail(item, index) {
      this.showDeviceContentDetail = !this.showDeviceContentDetail;
      this.showSearchDetail = !this.showSearchDetail
      this.choosedItem = item;
      this.choosedIndex = index;
    },
    judge(index) {
      let result = this.showDeviceContentDetail && this.choosedIndex === index;
      console.log("result:" + result);
      return result;
    },
    getResult() {
      if (this.searchKey !== "") {
        this.searchResults = [];
        for (let i in this.applyList) {
          for (let key in this.applyList[i]) {
            let temp = this.applyList[i][key] + ''
            if(temp.indexOf(this.searchKey) !== -1){
              this.searchResults.push(this.applyList[i]);
              break
            }
          }
        }
        console.dir(this.searchResults);
      }
    },
  },
  components: {
    XHeader,
    Cell,
    Group,
    CellBox,
    XInput,
    XTextarea,
    XButton,
    Radio,
    Checker,
    CheckerItem,
    Datetime,
    Search,
    Confirm
  }
};
</script>
<style scoped>
.applyForDevice,
.deviceContent {
  border: 2px solid #d9d9d9;
  box-shadow: 0px 0px 5px #888888;
  margin: 10px;
}
.deviceContent span {
  color: gray;
  font-size: 12px;
}
.assetType {
  display: flex;
}
.assetType span {
  border: 1px solid #d9d9d9;
  margin-right: 5px;
  padding: 5px;
  text-align: center;
  width: 100%;
}
.assetType .selected {
  border: 1px solid green;
}
.deviceContentDetail {
  margin: 10px 20px;
  border: 1px solid #d9d9d9;
  padding: 15px;
  line-height: 25px;
}
.deviceContentDetail div {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #d9d9d9;
}
.transferAsset {
  position: absolute;
  width: 80%;
  left: 10%;
  top: 30%;
  border: 1px solid green;
  background-color: white;
  border-radius: 5%;
  z-index: 999;
}
.chooseList {
  border: 1px solid #d9d9d9;
  margin: 30px;
}
ul {
  list-style: none;
}
.applyUserInfoList {
  display: flex;
  flex-direction: row-reverse;
  justify-content: center;
  padding: 0;
  overflow: auto;
}
.applyUserInfoList .applyUserInfoListLi {
  display: flex;
}
.applyUserInfoList i {
  color: gray;
  line-height: 70px;
  margin: 0 5px;
}
.applyUserInfoList .applyUserInfo {
  border: 1px solid #d9d9d9;
  box-sizing: border-box;
  height: 70px;
  min-width: 100px;
  height: auto;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 5px;
}
.applyUserInfoList .applyUserInfo span {
  text-align: center;
  line-height: 20px;
  color: gray;
  font-size: 12px;
}
.applyUserInfoList .applyUserInfo span:first-of-type {
  font-weight: bolder;
}
</style>
